#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow) {
    ui->setupUi(this);
    m_pLogin = new LoginWidget();
    m_pLogin->hide();
    clientTcp = new ClientTcp();

    connect(ui->btnLoginWidget, &QPushButton::clicked, this, [=](){
        m_pLogin->show();
        m_pLogin->switchToLoginPage();
    });
    connect(m_pLogin, &LoginWidget::onUserSuccess, this, &MainWindow::onLoginUserSuccess);
    connect(m_pLogin, &LoginWidget::onAdminSuccess, this, &MainWindow::onLoginAdminSuccess);
    connect(m_pLogin, &LoginWidget::loginRequested, clientTcp, &ClientTcp::startLogin);                // 连接信号和槽
    // 显式指定 Qt::QueuedConnection
    connect(clientTcp, &ClientTcp::loginResult,
            m_pLogin, &LoginWidget::onReceiveLogin,
            Qt::QueuedConnection); // 连接验证结果信号和槽

    connect(this, &MainWindow::destroyed, clientTcp, &ClientTcp::deleteLater);


    qDebug() << "MainWindow thread:" << QThread::currentThread();
}

void MainWindow::onLoginUserSuccess() {
//    m_pUser = new UserWidget();
//    connect(m_pLogin, &LoginWidget::onUserName, m_pUser, &UserWidget::onUserName);
//    m_pUser->show();
    //this->close();、
    if (m_pUser) {
            connect(m_pUser, &QObject::destroyed, this, [this]() {
                m_pUser = new UserWidget(this);
                connect(m_pLogin, &LoginWidget::onUserName, m_pUser, &UserWidget::onUserName, Qt::QueuedConnection);
                m_pUser->show();
            });
            m_pUser->deleteLater();
        } else {
            m_pUser = new UserWidget(this);
            connect(m_pLogin, &LoginWidget::onUserName, m_pUser, &UserWidget::onUserName, Qt::QueuedConnection);
            m_pUser->show();
        }
}

void MainWindow::onLoginAdminSuccess() {
//    m_pAdmin = new AdminWidget();
//    connect(m_pLogin, &LoginWidget::onUserName, m_pAdmin, &AdminWidget::onAdminName);
//    m_pAdmin->show();
    //this->close();
    if (m_pAdmin) {
            m_pAdmin->deleteLater(); // 安全删除
            m_pAdmin = nullptr;
        }
        m_pAdmin = new AdminWidget(this);
        connect(m_pLogin, &LoginWidget::onUserName, m_pAdmin, &AdminWidget::onAdminName, Qt::QueuedConnection);
        m_pAdmin->show();
}

MainWindow::~MainWindow() {
    if (m_pUser) {
            disconnect(m_pLogin, &LoginWidget::onUserName, m_pUser, &UserWidget::onUserName);
            m_pUser->deleteLater();
        }
        if (m_pAdmin) {
            disconnect(m_pLogin, &LoginWidget::onUserName, m_pAdmin, &AdminWidget::onAdminName);
            m_pAdmin->deleteLater();
        }
        disconnect(clientTcp, nullptr, this, nullptr);
        disconnect(clientTcp, nullptr, m_pLogin, nullptr);
    delete ui;
}




